<template>
	<div style="margin: 0 20px;">
		<div class="logo">
			<image src="/static/image/logo.png" />
		</div>
		<uni-forms :modelValue="loginForm">
			<!-- 输入账号（用户名） -->
			<uni-forms-item label="账号">
				<uni-easyinput type="text" v-model="loginForm.name" placeholder="请输入账号" />
			</uni-forms-item>
			<!-- 输入密码 -->
			<uni-forms-item label="密码">
				<uni-easyinput type="password" v-model="loginForm.password" placeholder="请输入密码" />
			</uni-forms-item>

			<!-- 登录按钮 -->
			<button style="margin-top: 10px;" type="primary" size="large" @click="onClickLogin">登录</button>

			<!-- 注册按钮 -->
			<button style="margin-top: 10px;" type="info" size="large" @click="onClickRegister">如果没有账号，请立即注册</button>
		</uni-forms>
	</div>
</template>

<script>
	import * as userAPI from "@/api/user.js" //导入登录接口
	import {
		getStorageUser,
		setStorageToken,
		setStorageUser,
	} from "@/utils/storage.js" //导入本地存储方法
	export default {
		name: "login",
		data() {
			return {
				loginForm: {
					name: "dingding", //用户名，仅仅测试方便
					password: "123456",
				},
				redirectPath: "",
			}
		},

		//生命周期钩子函数，在组件DOM元素加载好了后被调用
		onLoad(options) {
			console.log(options)
			this.redirectPath = options.redirect && decodeURIComponent(options.redirect);
			//初始赋值 ，从本地存储中获取用户名
			this.loginForm.name = getStorageUser().name;
		},

		methods: {
			onClickLogin() {
				if (this.loginForm.name === "" || this.loginForm.password === "") {
					uni.showToast({ title: "账号或密码不能为空", icon: "error" });
					return;
				}

				let params = this.loginForm;
				userAPI.login(params).then(result => {
					console.log(result);
					uni.showToast({
						title: "登录成功！",
						icon: "success"
					});
					//把返回的 id、name、avatar 、token 在本地保存  
					setStorageToken(result.data.token); //保存Token
					const user = {
						id: result.data.id,
						name: result.data.name,
						avatar: result.data.avatar,
					}
					setStorageUser(user); //保存用户数据

					//实现路由跳转页面 看看当前路由是否指定有重定向地址 否则跳转 user
					let toUrl = this.redirectPath || "/pages/user/user";

					//延时1秒后路由跳转
					setTimeout(() => {
						uni.reLaunch({
							url: toUrl,
						});
					}, 1000);
				}).catch((error) => {
					console.log(error);
				});
			},

			onClickRegister() {
				//路由跳转到用户注册页面				
				uni.navigateTo({
					url: "/pages/user/register"
				});
			}
		},
	}
</script>

<style lang="less" scoped="scoped">
	.logo {
		display: flex;
		justify-content: center;
	}

	.goto {
		display: block;
		margin-top: 25px;
		text-align: center;
	}
</style>